package com.csii.modules.online.cgreport.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csii.core.api.Result;
import com.csii.core.system.query.QueryGenerator;
import com.csii.core.system.vo.DynamicDataSourceModel;
import com.csii.core.util.SqlInjectionUtil;
import com.csii.modules.message.service.impl.SysMessageServiceImpl;
import com.csii.modules.online.cgform.util.CgformSqlUtil;
import com.csii.modules.online.cgreport.entity.OnlCgreportHead;
import com.csii.modules.online.cgreport.entity.OnlCgreportItem;
import com.csii.modules.online.cgreport.entity.OnlCgreportParam;
import com.csii.modules.online.cgreport.model.OnlCgreportModel;
import com.csii.modules.online.cgreport.service.IOnlCgreportHeadService;
import com.csii.modules.online.cgreport.service.IOnlCgreportItemService;
import com.csii.modules.online.cgreport.service.IOnlCgreportParamService;
import com.csii.modules.system.service.ISysBaseAPI;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@RestController("onlCgreportHeadController")
@RequestMapping({"/online/cgreport/head"})
public class OnlCgreportHeadController {
	private static final Logger log = LoggerFactory.getLogger(OnlCgreportHeadController.class);
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IOnlCgreportHeadService onlCgreportHeadService;
	@Autowired
	private IOnlCgreportParamService onlCgreportParamService;
	@Autowired
	private IOnlCgreportItemService onlCgreportItemService;
	@Autowired
	private SysMessageServiceImpl baseCommonService;

	/**
	 * @param sql
	 * @param dbKey
	 * @return
	 */
	@GetMapping({"/parseSql"})
	public Result<?> parseSql(@RequestParam(name = "sql") String sql, @RequestParam(name = "dbKey", required = false) String dbKey) {
		if (StringUtils.isNotBlank(dbKey)) {
			DynamicDataSourceModel sourceModel = this.sysBaseAPI.getDynamicDbSourceByCode(dbKey);
			if (sourceModel == null) {
				return Result.error("数据源不存在");
			}
		}

		HashMap map = new HashMap();
		ArrayList var4 = new ArrayList();
		ArrayList var5 = new ArrayList();
		List var6 = null;
		List var7 = null;

		try {
			log.info("Online报表，sql解析：" + sql);
			this.baseCommonService.addLog("Online报表，sql解析：" + sql, 2, 2);
			SqlInjectionUtil.specialFilterContentForOnlineReport(sql);
			var6 = this.onlCgreportHeadService.getSqlFields(sql, dbKey);
			var7 = this.onlCgreportHeadService.getSqlParams(sql);
			int i = 1;

			String var14;
			Iterator iterator;
			for (iterator = var6.iterator(); iterator.hasNext(); ++i) {
				var14 = (String) iterator.next();
				OnlCgreportItem cgreportItem = new OnlCgreportItem();
				cgreportItem.setFieldName(var14.toLowerCase());
				cgreportItem.setFieldTxt(var14);
				cgreportItem.setIsShow(1);
				cgreportItem.setOrderNum(i);
				cgreportItem.setId(CgformSqlUtil.getId());
				cgreportItem.setFieldType("String");
				var4.add(cgreportItem);
			}

			iterator = var7.iterator();

			while (iterator.hasNext()) {
				var14 = (String) iterator.next();
				OnlCgreportParam cgreportParam = new OnlCgreportParam();
				cgreportParam.setParamName(var14);
				cgreportParam.setParamTxt(var14);
				var5.add(cgreportParam);
			}

			map.put("fields", var4);
			map.put("params", var5);
			return Result.ok(map);
		} catch (Exception var12) {
			log.error(var12.getMessage(), var12);
			String var9 = "解析失败，";
			int var10 = var12.getMessage().indexOf("Connection refused: connect");
			if (var10 != -1) {
				var9 = var9 + "数据源连接失败.";
			} else if (var12.getMessage().indexOf("值可能存在SQL注入风险") != -1) {
				var9 = var9 + "SQL可能存在SQL注入风险.";
			} else if (var12.getMessage().indexOf("该报表sql没有数据") != -1) {
				var9 = var9 + "报表sql查询数据为空，无法解析字段.";
			} else if (var12.getMessage().indexOf("SqlServer不支持SQL内排序") != -1) {
				var9 = var9 + "SqlServer不支持SQL内排序.";
			} else {
				var9 = var9 + "SQL语法错误.";
			}

			return Result.error(var9);
		}
	}

	/**
	 * 列表分页
	 *
	 * @param  obj
	 * @param  pageNo
	 * @param  pageSize
	 * @param  req
	 * @return Result
	 */
	@GetMapping({"/list"})
	public Result<IPage<OnlCgreportHead>> list(OnlCgreportHead obj, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		Result result = new Result();
		QueryWrapper var6 = QueryGenerator.initQueryWrapper(obj, req.getParameterMap());
		Page page = new Page((long) pageNo, (long) pageSize);
		IPage iPage = this.onlCgreportHeadService.page(page, var6);
		result.setSuccess(true);
		result.setResult(iPage);
		return result;
	}

	/**
	 * 添加
	 * @param obj
	 * @return
	 */
	@PostMapping({"/add"})
	public Result<?> add(@RequestBody OnlCgreportModel obj) {
		Result result = new Result();

		try {
			//获取id
			String var3 = CgformSqlUtil.getId();
			OnlCgreportHead var4 = obj.getHead();
			List var5 = obj.getParams();
			List var6 = obj.getItems();
			var4.setId(var3);
			Iterator var7 = var5.iterator();

			while (var7.hasNext()) {
				OnlCgreportParam var8 = (OnlCgreportParam) var7.next();
				var8.setId((String) null);
				var8.setCgrheadId(var3);
			}

			var7 = var6.iterator();

			while (var7.hasNext()) {
				OnlCgreportItem var10 = (OnlCgreportItem) var7.next();
				var10.setId((String) null);
				var10.setFieldName(var10.getFieldName().trim().toLowerCase());
				var10.setCgrheadId(var3);
			}

			this.onlCgreportHeadService.save(var4);
			this.onlCgreportParamService.saveBatch(var5);
			this.onlCgreportItemService.saveBatch(var6);
			result.success("添加成功！");
		} catch (Exception var9) {
			log.error(var9.getMessage(), var9);
			result.error500("操作失败");
		}

		return result;
	}

	@PutMapping({"/editAll"})
	public Result<?> b(@RequestBody OnlCgreportModel var1) {
		try {
			return this.onlCgreportHeadService.editAll(var1);
		} catch (Exception var3) {
			log.error(var3.getMessage(), var3);
			return Result.error("操作失败");
		}
	}

	@DeleteMapping({"/delete"})
	public Result<?> a(@RequestParam(name = "id", required = true) String var1) {
		return this.onlCgreportHeadService.delete(var1);
	}

	@DeleteMapping({"/deleteBatch"})
	public Result<?> b(@RequestParam(name = "ids", required = true) String var1) {
		return this.onlCgreportHeadService.bathDelete(var1.split(","));
	}

	@GetMapping({"/queryById"})
	public Result<OnlCgreportHead> c(@RequestParam(name = "id", required = true) String var1) {
		Result var2 = new Result();
		OnlCgreportHead var3 = (OnlCgreportHead) this.onlCgreportHeadService.getById(var1);
		var2.setResult(var3);
		return var2;
	}
}
